/*
 *  Copyright (C) 2004 Cidero, Inc.
 *
 *  Permission is hereby granted to any person obtaining a copy of 
 *  this software to use, copy, modify, merge, publish, and distribute
 *  the software for any non-commercial purpose, subject to the
 *  following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
 *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY IN CONNECTION WITH THE SOFTWARE.
 * 
 *  File: $RCSfile: CDSFilter.java,v $
 *
 */

package com.cidero.upnp;


/**
 *
 *  Filter helper class for UPNP class heirarchy. Used to enable/suppress
 *  various optional properties when creating the DIDL-Lite XML object
 *  representation (UPNP control points sometimes request that certain
 *  properties are suppressed if they don't use them to save resources)
 *  
 *
 *  Typical filter string:
 *
 *   @id,@parentID,dc:title,dc:description,res,res@protocolInfo,
 *   container@childCount
 *   
 *   The @ sign refers to attributes that use the attribute convention
 *   in the DIDL-Lite as opposed to separate elements.
 *
 */
public class CDSFilter
{
  String   filter;
  boolean  enableAll;
  boolean  enableNone;
  String[] filterList;

  public CDSFilter( String filter )
  {
    this.filter = filter;

    enableAll = false;
    enableNone = false;

    if( filter == null || filter.equals("") )
    {
      enableNone = true;
    }
    else if( filter.equals("*") )
    {
      enableAll = true;
    }
    else
    {
      // Split the filter string into the individual components
      // separators are commas and/or spaces 
      // Note that if there is a 'res@protocolInfo' element attribute,
      // the 'res' element is implied (but sometimes both are specified)
      filterList = filter.split("[, ]");
    }
  }

  public boolean propertyEnabled( String prop )
  {
    if( enableAll )
      return true;
    else if( enableNone )
      return false;

    for( int n = 0 ; n < filterList.length ; n++ )
    {
      // exact match
      if( prop.equals( filterList[n] ) )
        return true;

      // match to element name of specified elem@attr pair 
      // TODO: this logic should be done at constructor time for efficiency
      int index;
      if( (index = filterList[n].indexOf('@')) != -1 )
      {
        if( prop.equals( filterList[n].substring( 0, index ) ) )
            return true;
      }
    }

    return false;

  }

  public String toString() {
    return filter;
  }

}
